package app.widget;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.longevityassistant.activity.R;

public class PAPopupWindow {
	private static PAPopupWindow mPaPopupWindow;
	/**
	 * mInflater
	 */
	private LayoutInflater mInflater;
	/**
	 * mWindowManager
	 */
	private WindowManager mWindowManager;
	/**
	 * popupWindow
	 */
	private PopupWindow mPopupWindow;
	/**
	 * mPopupView
	 */
	private TextView mPopupView;

	/**
	 * mDensity
	 */
	private float mDensity;
	
	/**
	 * mTag
	 */
	private Object mTag;

	public PAPopupWindow(Context context) {
		init(context);
	}

	public PAPopupWindow() {
	}

	public void init(Context context) {
		dismissPopupWindow();
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mWindowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics displayMetrics = new DisplayMetrics();
		mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
		mDensity = displayMetrics.density;
	}

	public static PAPopupWindow getInstance() {
		if (mPaPopupWindow == null) {
			mPaPopupWindow = new PAPopupWindow();
		}
		return mPaPopupWindow;
	}

	public void showPopupWindow(View view, String msg, int width, int height,
			int x, int y) {
		dismissPopupWindow();

		int[] location = new int[2];
		view.getLocationOnScreen(location);

		mPopupView = (TextView) mInflater.inflate(R.layout.app_widget_detail_view, null);
		mPopupView.setText(msg);
		mPopupView.setGravity(Gravity.CENTER);

		mPopupWindow = new PopupWindow(mPopupView, width, height);
		mPopupView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dismissPopupWindow();
			}
		});
		int viewX = location[0];
		int viewY = location[1];
		int pX = viewX + x;
		int pY = viewY + y;
		mPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, pX, pY);
		mPopupWindow.update();
	}

	/**
	 * 销毁信息窗口
	 */
	public void dismissPopupWindow() {
		if (mPopupView != null && mPopupView.isShown()) {
			mPopupWindow.dismiss();
		}
		mPopupView = null;
		mTag = null;
	}

	/**
	 * 判断窗口是否显示
	 * 
	 * @return 是否显示
	 */
	public boolean isShowing() {
		if (mPopupView != null && mPopupView.isShown()) {
			return true;
		}
		return false;
	}
	
	/**
	 * 获取TAG
	 * @return TAG
	 */
	public Object getTag() {
		return mTag;
	}

	/**
	 * 设置TAG
	 * @param tag tag
	 */
	public void setTag(Object tag) {
		mTag = tag;
	}
}
